<template>
  <div class="add-role">
    <header class="add-header">
      <div class="left">
        <span class="arrow" @click="$router.back()"
          ><i class="el-icon-arrow-left" />返回</span
        >
        <span>|</span>
        <span>{{ roleId ? '编辑角色' : '添加角色' }}</span>
      </div>
      <div class="right">黑马程序员</div>
    </header>
    <main class="add-main">
      <div class="step-container">
        <el-steps direction="vertical" :active="step">
          <el-step title="角色信息" />
          <el-step title="权限信息" />
          <el-step title="检查并完成" />
        </el-steps>
      </div>
      <!-- 角色信息 -->
      <div class="form-container" v-if="step === 1">
        <div class="title">角色信息</div>
        <div class="form">
          <el-form
            ref="infoForm"
            class="form-box"
            :model="roleForm"
            :rules="roleRules"
          >
            <el-form-item label="角色名称" prop="roleName">
              <el-input v-model="roleForm.roleName" />
            </el-form-item>
            <el-form-item label="角色描述" prop="remark">
              <el-input v-model="roleForm.remark" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!-- 权限信息 -->
      <div class="form-container" v-show="step === 2">
        <div class="title">权限配置</div>
        <div class="form">
          <div class="tree-wrapper">
            <div
              class="tree-item"
              v-for="(item, index) in permissionList"
              :key="item.id"
            >
              <div class="tree-title">
                {{ item.title }}
                <el-checkbox
                  class="selectAll"
                  v-model="item.checked"
                  @change="selectAll(item, index)"
                  >全选</el-checkbox
                >
              </div>
              <!-- 知识点：给elm ui的回调函数添加自定义的方法参数，记住这种使用套路 -->
              <el-tree
                @check-change="
                  (data, checked, indeterminate) =>
                    handleCheckChange(item, index, data, checked, indeterminate)
                "
                :data="item.children"
                ref="addTree"
                show-checkbox
                check-strictly
                default-expand-all
                node-key="id"
                :props="{ label: 'title' }"
              />
            </div>
          </div>
        </div>
      </div>
      <!-- 检查 -->
      <div class="form-container" v-show="step === 3">
        <div class="title">检查并完成</div>
        <div class="form">
          <div class="info">
            <div class="form-item">角色名称：{{ roleForm.roleName }}</div>
            <div class="form-item">角色描述：{{ roleForm.remark }}</div>
            <div class="form-item">角色权限：</div>
            <div class="tree-wrapper">
              <div
                v-for="item in permissionList"
                :key="item.id"
                class="tree-item"
              >
                <div class="tree-title">{{ item.title }}</div>
                <el-tree
                  ref="diabledTree"
                  :data="item.children"
                  show-checkbox
                  check-strictly
                  default-expand-all
                  node-key="id"
                  :props="{
                    label: 'title',
                    disabled: () => true
                  }"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="preStep" v-if="step !== 1">上一步</el-button>
        <el-button type="primary" @click="nextStep" v-if="step !== 3"
          >下一步</el-button
        >
        <el-button type="primary" v-if="step === 3" @click="submitRole">{{
          roleId ? '确认修改' : '确认添加'
        }}</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import {
  getTreeListAPI,
  createRoleUserAPI,
  getRoleDetailByUserAPI,
  updateRoleAPI
} from '@/api/system'
export default {
  name: 'AddRole',
  data () {
    return {
      step: 1,
      roleForm: {
        roleName: '',
        remark: '',
        perms: []
      },
      roleRules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        remark: [{ required: true, message: '请输入描述名称', trigger: 'blur' }]
      },
      permissionList: []
    }
  },
  methods: {
    // 编辑数据信息回显
    async getRoleDetailByUser () {
      const { data } = await getRoleDetailByUserAPI(this.roleId)
      delete data.userTotal
      this.roleForm = data
    },

    // 全选全消（属于自己学习拓展的功能）
    // 手动点击复选框 联动 全选框
    handleCheckChange (item, index, data, checked, indeterminate) {
      if (!checked) {
        item.checked = false
        item.checkedKeys = item.checkedKeys.filter(item => item !== data.id)
      } else {
        //避免重复添加数据
        if (!item.checkedKeys.includes(data.id)) {
          item.checkedKeys.push(data.id)
        }
        // 获取当前tree选中的节点与总节点数对比
        const checkedKeys = this.$refs.addTree[index].getCheckedKeys()
        const allIds = this.getIds(item.children)
        checkedKeys.length === allIds.length
          ? (item.checked = true)
          : (item.checked = false)
      }
    },
    /**
     * 获取当前tree下所有节点的id
     * @param list 最顶层的children数组
     * @param ids 数组，可不传
     */
    getIds (list, ids = []) {
      list.forEach(item => {
        if (item.id) {
          ids.push(item.id)
        }
        if (item.children) {
          this.getIds(item.children, ids)
        }
      })
      return ids
    },
    // 全选全消（知识点：【经验】每个tree都有一个checkedKeys来保存选中的节点id）
    selectAll (item, index) {
      const ids = this.getIds(item.children)
      item.checkedKeys = item.checked ? ids : []
      this.$refs.addTree[index].setCheckedKeys(item.checkedKeys)
    },

    // 提交添加角色请求
    async submitRole () {
      if (this.roleId) {
        await updateRoleAPI(this.roleForm)
        this.$message.success('修改角色成功')
      } else {
        await createRoleUserAPI(this.roleForm)
        this.$message.success('添加角色成功')
      }
      this.$router.go(-1)
    },
    // 获取权限信息
    async getTreeList () {
      let { data } = await getTreeListAPI()

      // 知识点：添加全选框的选中状态标识(建议初始化数据的时候就加上，这样无论何时使用属性都不会报错)
      data.map(item => {
        item.checked = false
        item.checkedKeys = []
        return data
      })
      this.permissionList = data
    },
    nextStep () {
      if (this.step === 3) return
      if (this.step === 1) {
        this.$refs.infoForm.validate(valid => {
          if (valid) {
            // 知识点：回调函数里面的return只会终止当前回调函数的执行，外面的代码不会受到影响
            // return false

            this.$refs.addTree.forEach((item, index) => {
              //只有编辑的时候回显
              if (this.roleId) {
                item.setCheckedKeys(this.roleForm.perms[index])
              }
            })

            this.step++

            // await this.getTreeList() // 知识点：如果调用的方法里面有异步操作的时候，注意看是否需要加await控制执行顺序
          }
        })
      } else if (this.step === 2) {
        const trees = this.$refs.addTree
        this.roleForm.perms = [] //必须每次都清空，重新获取，避免重复添加数据
        // 获取勾选数据
        trees.forEach(item => {
          this.roleForm.perms.push(item.getCheckedKeys())
        })
        // 知识点：flat函数，可以把多维数组合并为一个一维数组，传入参数可以自定义合并的维度数，详情参考mdn或ai

        if (this.roleForm.perms.flat().length === 0) {
          return this.$message.error('请勾选权限')
        }

        // 回显检查的数据
        const diabledTree = this.$refs.diabledTree
        diabledTree.forEach((item, index) => {
          item.setCheckedKeys(this.roleForm.perms[index]) //回显权限
        })
        this.step++
      }
    },
    preStep () {
      if (this.step === 1) return
      this.step--
    }
  },
  created () {
    // 知识点：【经验】一些基础性的数据最好在钩子函数里面获取。如下面这个方法放到钩子函数调用，提高加载效率。而不是点击下一步再调用，避免页面加载出现短暂空白页的情况
    this.getTreeList()
    if (this.roleId) {
      this.getRoleDetailByUser()
    }
  },
  computed: {
    roleId () {
      return this.$route.query.roleId
    }
  }
}
</script>
<style scoped lang="scss">
.add-role {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    position: fixed;
    top: 64px;
    bottom: 88px;
    width: 100%;
    overflow-y: auto;
    background: #f4f6f8;
    padding: 20px 230px;
    display: flex;
    .step-container {
      height: 400px;
      width: 200px;
    }
    .form-container {
      flex: 1;
      background-color: #fff;
      overflow-y: auto;
      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }
      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;
        .el-form {
          display: flex;
          flex-wrap: wrap;
        }
        .info {
          font-size: 14px;
          color: #666;
          .form-item {
            margin-bottom: 20px;
          }
        }
      }
      .form-box {
        width: 600px;
        display: flex;
        flex-direction: column;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
    z-index: 10001;
  }
  .tree-wrapper {
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    .tree-item {
      flex: 1;
      padding: 0px 4px;
      text-align: center;
      .tree-title {
        background: #f5f7fa;
        text-align: center;
        padding: 10px 0;
        margin-bottom: 12px;
      }

      // 自定义
      .selectAll {
        margin-left: 40px;
      }
    }
  }
}
</style>
